package com.mgq.algorithm.link;

import java.util.List;

/**
 * @author MaGuangQi
 * 反转单链表
 * <p>
 * 1->3->2
 * <p>
 * 一开始 pre=null,表示前一个节点
 * 反转
 *
 * <p>
 * <p>
 * <p>
 * 3->1->2
 * @date 2021-12-29 14:46
 **/
public class ReverseLink_206 {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(2);
        node1.next = node2;
        node2.next = node3;
        reverse(node1);
    }

    public static ListNode reverse(ListNode head) {

        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            //先保留当前节点的下一个节点,否则下一个节点指向前一个时,链表就断了
            ListNode next = cur.next;
            //将cur.next指向pre
            cur.next = pre;
            //当前节点变为前一个节点
            pre = cur;
            //指针后移
            cur = next;
        }
        //最后就是头
        return pre;
    }

    /**
     * 递归解决
     *
     * @param head
     * @return
     */
    public static ListNode reverse2(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        //递归下一个节点
        ListNode newHead = reverse2(head.next);
        //反转相邻节点
        head.next.next = head;
        //把头指向null,否则会是环
        head.next = null;
        //返回头
        return newHead;
    }
}


